from django.db.models import Q
from django.shortcuts import render, HttpResponse, redirect, reverse
from django.template import loader
from django.http import HttpResponseRedirect, JsonResponse
from django.contrib.auth.decorators import login_required
from django.urls.base import reverse_lazy
from django.views.decorators.http import require_http_methods, require_POST, require_GET
from .models import Blog, BlogComment, BlogCategory
from .forms import PubBlogForm


# Create your views here.

# 登录装饰器
def check_login(func):
    def check(request, *args, **kwargs):
        username = request.session.get("username")
        if username:
            return func(request, *args, **kwargs)
        else:
            return redirect(reverse('blogauth:login'))

    return check


def index(request):
    blogs = Blog.objects.all()
    return render(request, 'index.html', context={'blogs': blogs})


def blog_detail(request, blog_id):
    try:
        blog = Blog.objects.get(id=blog_id)
    except Exception as e:
        blog = None
    return render(request, 'blog_detail.html', context={'blog': blog})


# @check_login  # 自己定义的
# django自带的，使用反转
@require_http_methods(['GET', 'POST'])
@login_required(login_url=reverse_lazy("blogauth:login"))
def pub_blog(request):
    if request.method == 'GET':
        categories = BlogCategory.objects.all()
        return render(request, 'pub_blog.html', {'categories': categories})
    else:

        form = PubBlogForm(request.POST)
        if form.is_valid():
            print(111111)
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            category_id = form.cleaned_data['category']
            blog = Blog.objects.create(title=title, content=content, category_id=category_id, author=request.user)
            return JsonResponse({'code': 200, "message": '博客发布成功', "data": {'blog_id': blog.id}})
        else:
            print(form.errors)
            return JsonResponse({'code': 400, "message": "参数错误"})


@require_POST
@login_required()
def pub_comment(request):
    blog_id = request.POST.get('blog_id')
    content = request.POST.get('content')
    # print("222")
    BlogComment.objects.create(blog_id=blog_id, content=content, author=request.user)
    # 重新加载博客详情页
    return redirect(reverse('blog_detail', kwargs={'blog_id': blog_id}))


@require_GET
def search(request):
    q = request.GET.get('q')
    # 从博客的标题和内容中查找含有q关键字的博客
    blogs = Blog.objects.filter(Q(title__icontains=q) | Q(content__icontains=q)).all()
    return render(request, 'index.html', context={'blogs': blogs})
